package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.admin.entity.AdUser;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.IAdUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author xunyuhua
 * @since 2022-06-26
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断dto,name,password是否为空，为空给出提示信息
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_NULL);
        }

        //判断用户名是否存在，不存在给出登录错误提示信息
        //根据用户名查询用户信息
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(AdUser::getName, dto.getName());
        AdUser one = this.getOne(queryWrapper);
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.ADMIN_NOT_EXIST);
        }

        //用户名存在，核对密码
        String passWord = dto.getPassword() + one.getSalt();
        passWord = DigestUtils.md5Hex(passWord);
        if (!StringUtils.equals(passWord, one.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        Map resultMap = new HashMap();
        //去除用户的敏感信息
        one.setPassword("");
        one.setSalt("");
        one.setPhone("");
        resultMap.put("user",one);

        Map claimMaps = new HashMap();
        claimMaps.put("userId",one.getId());
        claimMaps.put("name",one.getName());
        String token = AppJwtUtil.getToken(claimMaps);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);


    }
}
